package info.rongtong.action;

import info.rongtong.domain.Account;
import info.rongtong.service.inter.AccountServiceInter;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport{

	private static final long serialVersionUID = 2591023904033339282L;
	private Account account;
	private String code;
	private AccountServiceInter accountServiceImpl;
	private HttpServletRequest request = ServletActionContext.getRequest();
	private Map<String,Object> map = new HashMap<String, Object>();
	
	
	public String login() {
		Account account2 = accountServiceImpl.checkUser(account);
		if(account2!=null){
			request.getSession().setAttribute("adminUser", account2);
			//因为引用传递，最后结果将不出偏差，所以采用了人工赋值
			account.setAid(account2.getAid());
			//将信息更新到数据库
			//上将登陆的ip，上次登陆的时间
			String ip = request.getHeader("x-forwarded-for");  
		    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
		        ip = request.getHeader("Proxy-Client-IP");  
		    }  
		    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
		        ip = request.getHeader("WL-Proxy-Client-IP");  
		    }  
		    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
		        ip = request.getRemoteAddr();  
		    }  
		    account.setAlastLoginIp(ip);
		    account.setAlastLoginTime(new java.util.Date());
		    account.setAuserName(account2.getAuserName());
		    accountServiceImpl.saveOrUpdate(account);
			return "loginOk";
		}
		else{
			request.setAttribute("err", "用户名或者密码错误！");
			return "loginErr";
		}
	}
	
	/**
	 * 验证码验证
	 * @return
	 */
	public String checkCode(){
		String sessionCode = request.getSession().getAttribute("ccode").toString();
		if(sessionCode.equals(code)){
			map.put("result", true);
		}else{
			map.put("result", false);
		}
		return "remote";
	}

	/**
	 * 自动生成
	 */

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public AccountServiceInter getAccountServiceImpl() {
		return accountServiceImpl;
	}

	public void setAccountServiceImpl(AccountServiceInter accountServiceImpl) {
		this.accountServiceImpl = accountServiceImpl;
	}
	public Map<String, Object> getMap() {
		return map;
	}

}
